
#include "httplib_server_session.h"
#include "log_helper.h"
#include "global_config.h"
#include "dump_trace.h"
#include "ini_utils.hpp"
#include "sqldb_config.h"
#include "reflection_test.h"

#define CONFIG_PATH "./httpserver.cfg"

USING_NS

bool load_cfg(const std::string & path){
    auto config = Singleton<GlobalConfig>::instance();
    ltmit::CIniParser parser;
    int  ret = parser.parseFile(path.c_str());
    if(ret != 0){
        LOG_ERROR(MAIN_LOG, "parse config file error");
        return false;
    }
    config->server.port = parser.cxx_getint("server", "port");

    config->log.level = spdlog::level::from_str(parser.cxx_get_value("log", "level"));
    config->log.max_size_mb = parser.cxx_getint("log", "max_size_mb");
    config->log.max_count = parser.cxx_getint("log", "max_count");

    config->mysql.need_connect = parser.cxx_getint("sqldb", "db_need_connect");
    config->mysql.type = parser.cxx_get_value("sqldb", "db_type");
    config->mysql.conn_url = parser.cxx_get_value("sqldb", "db_conn_url");
    config->mysql.uname = parser.cxx_get_value("sqldb", "db_uname");
    config->mysql.pswd = parser.cxx_get_value("sqldb", "db_pswd");
    config->mysql.init_paras = parser.cxx_get_value("sqldb", "db_init_paras");

    return true;
}

__attribute__((constructor)) void init(void){
    LogHelper::logBasicInit();
    LOG_INFO(MAIN_LOG, "log basic init finish!");
    load_cfg(CONFIG_PATH);
    LOG_INFO(MAIN_LOG, "load config file finish!");
    LogHelper::logInit();
    LOG_INFO(MAIN_LOG, "log init finish!");
}

int main(){
    {
        // 测试c++反射的使用
        auto actor = std::shared_ptr<ReflectionTestI>(static_cast<ReflectionTestI*>(ReflectionFactory::create_actor("ReflectionTest")));
        if(actor){
            std::string msg = std::string("ReflectionTestI success!");
            actor->printf(msg);
        }
    }
    // 注册异常处理捕获
    registerExceptionHandler();

    auto config = Singleton<GlobalConfig>::instance();
    // mysql connect
    if(config->mysql.need_connect==1){
        bool ret = sqldb_init(config->mysql.type,
                             config->mysql.conn_url,
                             config->mysql.uname,
                             config->mysql.pswd,
                             config->mysql.init_paras);
        if(!ret){
            return 0;
        }
        LOG_INFO(MAIN_LOG ,"sql db init finish!");
        if (!sqldb_load_config()){
            LOG_ERROR(MAIN_LOG, "sql db config file load finish!");
        }
    }

    LOG_INFO(MAIN_LOG ,"http server start up with {}", config->server.port);

    httplib_service_start(config->server.port);

    return 0;
}